//
//  IAAHisTaskVC.m
//  iPadAuditAuthorise
//
//  Created by XiangDongMBP on 16/9/2.
//  Copyright © 2016年 XiangDong. All rights reserved.
//

#import "IAAHisTaskVC.h"
#import "IAAAuthCheckTHeader.h"
#import "IAAHisTaskTCell.h"
#import <MJRefresh.h>
#import "IAAHisTaskModel.h"
#import "IAAHisTaskDetailVC.h"
#import <UIScrollView+EmptyDataSet.h>

@interface IAAHisTaskVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IAAHisTaskModel *model;

@end

static NSInteger const kPageSize = 15;  //!< 每次请求的记录数a
static NSString * const reuseHeaderId = @"IAAAuthCheckTCell";
static NSString * const reuseCellId = @"IAAHisTaskTCell";

@implementation IAAHisTaskVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //设置导航栏
    [self initNavigationBar];
    //設置子Views
    [self initSubViews];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initNavigationBar {
    self.navigationItem.title = @"历史审核任务查看";
}

- (void)initSubViews {
    [self.tableView registerClass:[IAAAuthCheckTHeader class] forHeaderFooterViewReuseIdentifier:reuseHeaderId];
    UINib *cellNib = [UINib nibWithNibName:reuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:reuseCellId];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    
    //下拉、上拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    
    // 触发刷新
    [self.tableView.mj_header beginRefreshing];
}

- (void)refreshWholeView {
    if (self.model.taskList.count >= self.model.totalCount) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    [self.tableView reloadData];
}

#pragma mark - <UITableViewDelegate>代理
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    IAAAuthCheckTHeader *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:reuseHeaderId];
    NSArray<NSString *> *array = @[@"流水号", @"终端号", @"交易名称", @"客户名称", @"帐号", @"一审状态", @"二审状态"];
    [view configViewWithArrar:array];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    IAAHisTaskDetailVC *vc = [[IAAHisTaskDetailVC alloc] init];
    vc.model = self.model.taskList[indexPath.row];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    nav.modalPresentationStyle = UIModalPresentationPageSheet;
    
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - <UITableViewDataSource>代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.taskList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IAAHisTaskTCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.model.taskList.count) {
        [cell configViewWithData:self.model.taskList[indexPath.row]];
    }
    return cell;
}

#pragma mark - <DZNEmptyDataSetSource>代理
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"Glo_load_sad"];
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"无数据"];
}

#pragma mark - <DZNEmptyDataSetDelegate>代理
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - 网络请求
- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    NSInteger startIndex = isHeader ? 0 : self.model.taskList.count;
    NSString *urlStr = [IAAUrlProtocolMerge appAuthCheckHisTaskList];
    NSDictionary *pars = @{@"orgNo"  : IAA_APP_DELEGATE.organizeId,
                           @"token" : IAA_APP_DELEGATE.token,
                           @"osName": @"iOS",
                           @"startIndex" : @(startIndex),
                           @"pageSize": @(kPageSize)};
    
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"历史审核任务查看返回 %@", responseObject);
        [self tableViewEndRefresh:isHeader];
        IAAHisTaskModel *temp = [IAAHisTaskModel yy_modelWithJSON:responseObject];
        if (isHeader || !self.model) {
            self.model = temp;
        } else {
            [self.model addMoreWithData:temp];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"历史审核任务查看失败 %@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

@end
